package website.seamonster.ethegg.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import website.seamonster.ethegg.dataobject.Account;
import website.seamonster.ethegg.enums.ResultEnum;
import website.seamonster.ethegg.exception.EthException;
import website.seamonster.ethegg.repository.AccountRepository;

import java.math.BigDecimal;

/**
 * Created by 罗海量
 * 2018-07-24 22:43
 */
@lombok.extern.slf4j.Slf4j
@Service
public class AccountService {
    @Autowired
    private AccountRepository accountRepository;

    /**
     * 收入
     * @param userId
     * @param amt
     */
    @Transactional
    public void increase(String userId, BigDecimal amt){
        Account ac = accountRepository.findOne(userId);
        if (ac==null){
            throw new EthException(ResultEnum.USER_NOT_EXIST);
        }
        ac.setBalance(ac.getBalance().add(amt));
    }

    /**
     * 扣钱
     * @param userId
     * @param amt
     */
    @Transactional
    public void decrease(String userId, BigDecimal amt){
        Account ac = accountRepository.findOne(userId);
        if (ac==null){
            throw new EthException(ResultEnum.USER_NOT_EXIST);
        } else if (amt.compareTo(ac.getBalance()) > 0){
            throw new EthException(ResultEnum.NO_MONEY);
        }
        ac.setBalance(ac.getBalance().add(amt.negate()));
    }

    public BigDecimal getBalanceByUser(String userId){
        Account ac = accountRepository.findOne(userId);
        if (ac==null){
            throw new EthException(ResultEnum.USER_NOT_EXIST);
        }
        return ac.getBalance();
    }

}
